package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    @Autowired
    GeneratePageService generatePageService;
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {

        //1.封装 对象
        ApArticle apArticle = dtoToArticle(articleDto);
        // 2. 保存或修改文章
        Long articleId = saveOrUpdateArticle(apArticle);
        // 3. 保存 文章 内容 和 配置 信息
        saveContentAndConfig(articleId, articleDto.getContent());
        //页面静态化
        generatePageService.generateArticlePage(articleDto.getId());

        return ResponseResult.okResult(apArticle.getId());

    }
    @Autowired
    ApArticleMapper apArticleMapper;

    @Value("file.minio.readPath")
    String readPath;

    @Value("file.oss.web-site")
    String webSite;


    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //1.参数检查 分页 频道标签 最大时间 最小时间
        if (dto == null) {
            dto = new ArticleHomeDto();
        }
        if (dto.getSize() == null || dto.getSize() < 1) {
            dto.setSize(10);
        }
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //2.调用mapper 进行两表查询
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle apArticle : apArticles) {
            apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
        }
        //3. 返回结果
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        responseResult.setHost(webSite);
        return responseResult;

    }

    private void saveContentAndConfig(Long articleId, String content) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(articleId);// 文章id
        apArticleConfig.setIsComment(true);// 是否允许评论
        apArticleConfig.setIsForward(true);// 是否允许转发
        apArticleConfig.setIsDown(false);// 是否下架
        apArticleConfig.setIsDelete(false);// 是否删除
        apArticleConfigMapper.insert(apArticleConfig);

        //保存文章article_content 数据
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(content);// 文章内容
        apArticleContent.setArticleId(articleId); // 文章id
        apArticleContentMapper.insert(apArticleContent);
    }

    /**
     * 保存或修改文章信息
     */
    private Long saveOrUpdateArticle(ApArticle apArticle) {
        if (apArticle.getId() == null) {
            // 普通文章
            apArticle.setCollection(0);//收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);//评论数
            apArticle.setViews(0);//阅读数
            // 保存
            save(apArticle);
        } else {
            // 修改文章 删除之前关联的配置信息 内容信息
            ApArticle article = getById(apArticle.getId());
            if (article == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 修改文章
            updateById(apArticle);
            // 删除之前配置信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            // 删除之前内容信息
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));

        }
        return apArticle.getId();
    }
    /**
     * 基于dto封装 Article
     */
    private ApArticle dtoToArticle(ArticleDto articleDto) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        // 根据自媒体用户id  查询 作者iｄ
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery()
                .eq(ApAuthor::getWmUserId, articleDto.getWmUserId())
        );
        if (apAuthor == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
            apArticle.setAuthorName(apAuthor.getName());
            apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
            return apArticle;
    }
}